# -*-coding:utf-8-*-
# -*- coding: utf-8 -*-
# @Time    : 2022/10/14 11:41
# @Author  : gaojy
# @Site    : 
# @File    : handler_case.py
# @Software: PyCharm
import json
import re
import yaml
from common.common_function import get_parent_path, read_csv
from jsonpath import jsonpath
import copy


class HandleCase:
    # 从yaml中读取测试用例并组装成列表传递pytest.mark.parameterize的参数
    @staticmethod
    def read_case(path):
        with open(get_parent_path() + path, "r+", encoding = "utf8") as f:
            case_list = yaml.load(f.read(), yaml.FullLoader)
            new_case_list = []
            for case_dict in case_list:
                # 判断有无参数化
                if "parameters" in case_dict:
                    new_case = HandleCase.get_parameters(case_dict)
                    new_case_list = new_case_list + new_case
                else:
                    new_case_list.append(case_dict)
            return new_case_list

    # 参数化csv文件替换
    @staticmethod
    def get_parameters(case_dict: dict):
        params_path = jsonpath(case_dict, "$..parameters")[0]
        try:
            csv_result = read_csv(params_path)
            case_str = json.dumps(case_dict, ensure_ascii = False)
            # 查找整个用例中的标识形成列表
            old_value_list = re.findall(r"\$csv{\w+}", case_str)
            new_list = []
            for csv_dict in csv_result:
                # 深拷贝得到的值赋给
                new_case_str = copy.copy(case_str)
                for old_value in old_value_list:
                    csv_dict_key = re.findall(r"\$csv{(\w+)}", old_value)[0]
                    new_case_str = new_case_str.replace(old_value, csv_dict[csv_dict_key])
                new_list.append(json.loads(new_case_str))
            return new_list
        except Exception:
            print("csv文件有误")


if __name__ == "__main__":
    h = HandleCase()
    result = h.read_case(r"/testcase/project_name/module_name/login.yaml")
    for data in result:
        print(data)
